####################################################################################
################################### MutatationTime
## 建立Input
cat ${config_path}/tumor_normal.MSI.list | grep -v Normal | awk -F, '{print $1}' | sort -u | xargs -P 10 -i sh -c '
sh ${scripts_path}/mutationTime/MutationTime_GetInput.sh {}
'

## 检查是否所有样本都跑完
#finishSample=`ls ${MutationTime_path}/result | grep mutTime.tsv  | awk -F'_CCF_mutTime' '{print $1}' | tr '\n' '|' | sed 's/|$//'`

## 默认的cluster适用于30x的WGS测序，认为90%为克隆，10%为亚克隆，200x的wes会有许多亚克隆，原始的cluster不合适
## 计算突变时期
## 使用pyclone推测的时期
cat ${config_path}/tumor_normal.MSI.list | grep -v Normal | awk -F, '{print $1}' | sort -u | xargs -P 40 -i sh -c '
${Rscript_mutationTime} ${scripts_path}/mutationTime/MutationTime_run.combineCluster.R \
--sample {} \
--info_file ${config_path}/tumor_normal.class.MSI.list \
--ccf_file ${Titan_path}/chat/{}_CHAT.txt \
--vcf_file ${MutationTime_path}/input/{}.vcf \
--cnv_file ${MutationTime_path}/input/{}.seg \
--purity_file ${Titan_path}/Purity_titan.final.reviseLowPurity.tsv \
--out_path ${MutationTime_path}/result/ \
--cluster_path ${Pyclone_path}/result/All \
--chr_len ${ref_path}/seq/GRCh37.fa.fai \
--bedtools_path ${tools_path}/StandTools \
2> ${log_path}/{}_MutationTimeRun.log
'

## 检查所有样本不同时期的突变数量
cat ${config_path}/tumor_normal.MSI.list | grep -v Normal | awk -F, '{print $1}' | sort -u | xargs -P 10 -i sh -c '
${Rscript} ${scripts_path}/mutationTime/MutationTime_GetTimeDistribution.R \
--sample {} \
--purity_file ${Titan_path}/Purity_titan.final.reviseLowPurity.tsv \
--input_file ${MutationTime_path}/result/{}_CCF_mutTime.tsv  \
--out_path ${MutationTime_path}/distribution  \
2> ${log_path}/{}_MutationTime_GetTimeDistribution.log
'

## 每个样本，不同时期的克隆突变数目有多少
rm -rf ${MutationTime_path}/distribution/All_mutTime.MSI.tsv
cat ${MutationTime_path}/distribution/* | grep Purity | head -1 > ${MutationTime_path}/distribution/All_mutTime.MSI.tsv
for Tumor in `cat ${config_path}/tumor_normal.MSI.list | grep -v Normal | awk -F, '{print $1}' | sort -u`
do
cat ${MutationTime_path}/distribution/${Tumor}_mutTime_stat.tsv | grep -v Purity >> ${MutationTime_path}/distribution/All_mutTime.MSI.tsv
done

####################################################################################
## 合并每个突变的克隆时期
rm -rf ${MutationTime_path}/result/All_CCF_mutTime.MSI.tsv 
cat ${MutationTime_path}/result/J*CCF_mutTime.tsv | grep -m 1 Chr | awk -F'\t' '{OFS="\t"}{print "Sample",$0}' \
> ${MutationTime_path}/result/All_CCF_mutTime.MSI.tsv 

for Tumor in `cat ${config_path}/tumor_normal.MSI.list | grep -v Normal | awk -F, '{print $1}' | sort -u`
do
echo ${Tumor}
cat ${MutationTime_path}/result/${Tumor}_CCF_mutTime.tsv | grep -v Chr | awk -F'\t' '{OFS="\t"}{print Sample,$0}' Sample=${Tumor} \
>> ${MutationTime_path}/result/All_CCF_mutTime.MSI.tsv
done
